<template>
  <div class="security-vulnerability-container">
    <div class="header-section">
      <h2>安全漏洞管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button
          v-if="selectedVulnerabilities.length > 0"
          type="success"
          @click="batchMarkFixed"
        >
          <el-icon><Check /></el-icon>
          批量标记修复
        </el-button>
        <el-button
          v-if="selectedVulnerabilities.length > 0"
          type="info"
          @click="batchConfirm"
        >
          <el-icon><CircleCheck /></el-icon>
          批量确认
        </el-button>
        <el-button
          v-if="selectedVulnerabilities.length > 0"
          type="danger"
          @click="batchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 漏洞统计卡片 -->
    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card total">
            <div class="stat-content">
              <div class="stat-number">{{ totalVulnerabilities }}</div>
              <div class="stat-label">总漏洞数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card critical">
            <div class="stat-content">
              <div class="stat-number">{{ criticalVulnerabilities }}</div>
              <div class="stat-label">严重漏洞</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card high">
            <div class="stat-content">
              <div class="stat-number">{{ highVulnerabilities }}</div>
              <div class="stat-label">高危漏洞</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6">
          <el-card class="stat-card pending">
            <div class="stat-content">
              <div class="stat-number">{{ pendingVulnerabilities }}</div>
              <div class="stat-label">待处理</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-filter-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索漏洞名称/ID"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchForm.severity"
            placeholder="选择严重程度"
            clearable
          >
            <el-option label="全部" value="" />
            <el-option label="严重" value="critical" />
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
                v-model="searchForm.status"
                placeholder="选择状态"
                clearable
              >
                <el-option label="全部" value="" />
                <el-option label="待处理" value="pending" />
                <el-option label="处理中" value="processing" />
                <el-option label="已修复" value="fixed" />
                <el-option label="已确认" value="confirmed" />
                <el-option label="误报" value="false_positive" />
                <el-option label="重新检查中" value="in_recheck" />
              </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="searchVulnerabilities">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 漏洞列表表格 -->
    <el-table
      v-loading="loading"
      :data="paginatedVulnerabilities"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="漏洞ID" width="120" />
      <el-table-column prop="name" label="漏洞名称" min-width="200">
        <template #default="{ row }">
          <span @click="viewVulnerabilityDetails(row)" class="link-text">
            {{ row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="漏洞类型" width="150">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="severity" label="严重程度" width="120">
        <template #default="{ row }">
          <el-tag :type="getSeverityTagType(row.severity)">
            {{ getSeverityText(row.severity) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="发现时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="target" label="影响目标" min-width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="viewVulnerabilityDetails(row)">
            详情
          </el-button>
          <el-button type="danger" size="small" @click="deleteVulnerability(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredVulnerabilities.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 漏洞详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentVulnerability ? `漏洞详情 - ${currentVulnerability.name}` : '漏洞详情'"
      width="700px"
    >
      <div v-if="currentVulnerability" class="vulnerability-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="漏洞ID">{{ currentVulnerability.id }}</el-descriptions-item>
          <el-descriptions-item label="漏洞名称">{{ currentVulnerability.name }}</el-descriptions-item>
          <el-descriptions-item label="漏洞类型">
            <el-tag :type="getTypeTagType(currentVulnerability.type)">{{ currentVulnerability.type }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag :type="getSeverityTagType(currentVulnerability.severity)">
              {{ getSeverityText(currentVulnerability.severity) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getStatusTagType(currentVulnerability.status)">
              {{ getStatusText(currentVulnerability.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" v-if="currentVulnerability.updated_at">
            {{ formatDate(currentVulnerability.updated_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="发现时间">{{ formatDate(currentVulnerability.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="影响目标">{{ currentVulnerability.target }}</el-descriptions-item>
          <el-descriptions-item label="漏洞描述">{{ currentVulnerability.description }}</el-descriptions-item>
          <el-descriptions-item label="修复建议">{{ currentVulnerability.remediation }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="updateVulnerabilityStatus('fixed')" v-if="currentVulnerability?.status !== 'fixed'">
          标记为已修复
        </el-button>
        <el-button type="info" @click="updateVulnerabilityStatus('confirmed')" v-if="currentVulnerability?.status !== 'confirmed'">
          确认漏洞
        </el-button>
        <el-button type="warning" @click="updateVulnerabilityStatus('false_positive')" v-if="currentVulnerability?.status !== 'false_positive'">
          标记误报
        </el-button>
        <el-button type="info" @click="recheckVulnerability">重新检查</el-button>
        <el-button type="danger" @click="deleteVulnerability(currentVulnerability.id)">
          删除
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox, ElDialog, ElDescriptions, ElPagination } from 'element-plus';
import { 
  Refresh, 
  Search, 
  Check, 
  CircleCheck, 
  Delete 
} from '@element-plus/icons-vue';
import apiService from '../services/apiService';

// 响应式数据
const loading = ref(false);
const vulnerabilities = ref([]);
const selectedVulnerabilities = ref([]);
const searchForm = ref({
  keyword: '',
  severity: '',
  status: ''
});
const dialogVisible = ref(false);
const currentVulnerability = ref(null);
const pagination = ref({
  currentPage: 1,
  pageSize: 10
});

// 已移除模拟API服务，使用真实的apiService接口与后端交互

// 日期格式化函数
const formatDate = (dateString) => {
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    return '-';
  }
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取漏洞类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    '注入': 'warning',
    'XSS': 'danger',
    '配置错误': 'info',
    '访问控制': 'error',
    '代码执行': 'critical'
  };
  return typeMap[type] || 'primary';
};

// 获取严重程度标签类型
const getSeverityTagType = (severity) => {
  const severityMap = {
    'critical': 'danger',
    'high': 'warning',
    'medium': 'primary',
    'low': 'info'
  };
  return severityMap[severity] || 'default';
};

// 获取严重程度文本
const getSeverityText = (severity) => {
  const severityMap = {
    'critical': '严重',
    'high': '高',
    'medium': '中',
    'low': '低'
  };
  return severityMap[severity] || severity;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'processing': 'primary',
    'fixed': 'success',
    'confirmed': 'info',
    'false_positive': 'info',
    'in_recheck': 'primary'
  };
  return statusMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'processing': '处理中',
    'fixed': '已修复',
    'confirmed': '已确认',
    'false_positive': '误报',
    'in_recheck': '重新检查中'
  };
  return statusMap[status] || status;
};

// 统计计算
const totalVulnerabilities = computed(() => vulnerabilities.value.length);
const criticalVulnerabilities = computed(() => 
  vulnerabilities.value.filter(item => item.severity === 'critical').length
);
const highVulnerabilities = computed(() => 
  vulnerabilities.value.filter(item => item.severity === 'high').length
);
const pendingVulnerabilities = computed(() => 
  vulnerabilities.value.filter(item => item.status === 'pending').length
);

// 筛选后的漏洞列表
const filteredVulnerabilities = computed(() => {
  let result = [...vulnerabilities.value];
  
  // 按关键字筛选
  if (searchForm.value.keyword) {
    const keyword = searchForm.value.keyword.toLowerCase();
    result = result.filter(item => 
      item.id.toLowerCase().includes(keyword) || 
      item.name.toLowerCase().includes(keyword)
    );
  }
  
  // 按严重程度筛选
  if (searchForm.value.severity) {
    result = result.filter(item => item.severity === searchForm.value.severity);
  }
  
  // 按状态筛选
  if (searchForm.value.status) {
    result = result.filter(item => item.status === searchForm.value.status);
  }
  
  // 按时间倒序排序
  result.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  
  return result;
});

// 分页后的数据
const paginatedVulnerabilities = computed(() => {
  const { currentPage, pageSize } = pagination.value;
  const start = (currentPage - 1) * pageSize;
  const end = start + pageSize;
  return filteredVulnerabilities.value.slice(start, end);
});

// 监听筛选条件变化，重置页码
watch(filteredVulnerabilities, () => {
  pagination.value.currentPage = 1;
});

// 加载漏洞数据
const loadVulnerabilities = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: pagination.value.currentPage,
      page_size: pagination.value.pageSize,
      keyword: searchForm.value.keyword,
      severity: searchForm.value.severity,
      status: searchForm.value.status
    };
    
    // 调用真实API获取数据
    const response = await apiService.getVulnerabilities(params);
    vulnerabilities.value = response.data || [];
    // 更新分页信息
    if (response.total) {
      pagination.value.total = response.total;
    }
  } catch (error) {
    console.error('获取漏洞数据失败:', error);
    ElMessage.error('加载失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  selectedVulnerabilities.value = [];
  pagination.value.currentPage = 1;
  loadVulnerabilities();
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedVulnerabilities.value = selection;
};

// 查看漏洞详情
const viewVulnerabilityDetails = (vulnerability) => {
  currentVulnerability.value = { ...vulnerability };
  dialogVisible.value = true;
};

// 重新检查漏洞
const recheckVulnerability = async () => {
  if (!currentVulnerability.value) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要重新检查漏洞 ${currentVulnerability.value.id} 吗？\n重新检查将使用最新的扫描规则验证此漏洞是否仍然存在。`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'primary'
      }
    );
    
    loading.value = true;
    
    // 更新状态为正在重新检查
    await apiService.updateVulnerabilityStatus(currentVulnerability.value.id, 'in_recheck', '用户手动触发重新检查');
    
    // 更新本地状态
    const index = vulnerabilities.value.findIndex(item => item.id === currentVulnerability.value.id);
    if (index !== -1) {
      vulnerabilities.value[index].status = 'in_recheck';
      vulnerabilities.value[index].updated_at = new Date().toISOString();
      currentVulnerability.value.status = 'in_recheck';
      currentVulnerability.value.updated_at = vulnerabilities.value[index].updated_at;
    }
    
    ElMessage.success('漏洞重新检查已启动，请稍后查看结果');
  } catch (error) {
    // 用户取消操作或API错误
    if (error !== 'cancel') {
      console.error('重新检查漏洞失败:', error);
      ElMessage.error('重新检查失败，请重试');
    }
  } finally {
    loading.value = false;
  }
};

// 更新漏洞状态
const updateVulnerabilityStatus = async (status, reason = '') => {
  if (!currentVulnerability.value) return;
  
  try {
    const id = currentVulnerability.value.id;
    
    // 如果是标记为误报，要求输入原因
    let finalReason = reason;
    if (status === 'false_positive' && !reason) {
      const result = await ElMessageBox.prompt(
        '请输入误报原因:',
        '标记为误报',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请描述为什么这是一个误报...',
          inputValidator: (value) => {
            if (!value || value.trim().length < 5) {
              return '请提供至少5个字符的误报原因';
            }
            return true;
          }
        }
      );
      finalReason = result.value;
    }
    
    // 调用API更新状态
    await apiService.updateVulnerabilityStatus(id, status, finalReason || (status === 'fixed' ? '用户手动标记为已修复' : '用户确认漏洞'));
    
    // 更新本地数据
    const index = vulnerabilities.value.findIndex(item => item.id === id);
    if (index !== -1) {
      vulnerabilities.value[index].status = status;
      vulnerabilities.value[index].updated_at = new Date().toISOString();
      currentVulnerability.value.status = status;
      currentVulnerability.value.updated_at = vulnerabilities.value[index].updated_at;
    }
    
    // 根据不同状态显示不同的成功消息
    const statusMessages = {
      'fixed': '漏洞已标记为已修复',
      'confirmed': '漏洞已确认',
      'false_positive': '漏洞已标记为误报',
      'in_recheck': '漏洞已提交重新检查'
    };
    
    ElMessage.success(statusMessages[status] || `漏洞状态已更新为${status}`);
  } catch (error) {
    // 用户取消操作或API错误
    if (error !== 'cancel') {
      console.error('更新漏洞状态失败:', error);
      ElMessage.error('更新失败，请重试');
    }
  }
};

// 删除漏洞
const deleteVulnerability = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个漏洞吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await apiService.deleteVulnerability(id);
    vulnerabilities.value = vulnerabilities.value.filter(item => item.id !== id);
    
    // 如果正在查看被删除的漏洞，关闭对话框
    if (currentVulnerability.value && currentVulnerability.value.id === id) {
      dialogVisible.value = false;
      currentVulnerability.value = null;
    }
    
    ElMessage.success('删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除漏洞失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 批量标记为已修复
const batchMarkFixed = async () => {
  if (selectedVulnerabilities.value.length === 0) {
    ElMessage.warning('请先选择要标记为已修复的漏洞');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${selectedVulnerabilities.value.length} 个漏洞标记为已修复吗？`,
      '批量操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    );
    
    loading.value = true;
    
    // 获取所有选中的漏洞ID
    const vulnIds = selectedVulnerabilities.value.map(vuln => vuln.id);
    
    // 调用批量更新API
    await apiService.batchUpdateVulnerabilityStatus(vulnIds, 'fixed');
    
    // 更新本地数据
    for (const vuln of selectedVulnerabilities.value) {
      const index = vulnerabilities.value.findIndex(item => item.id === vuln.id);
      if (index !== -1) {
        vulnerabilities.value[index].status = 'fixed';
        vulnerabilities.value[index].updated_at = new Date().toISOString();
      }
    }
    
    // 显示成功消息
    ElMessage.success(`成功将 ${selectedVulnerabilities.value.length} 个漏洞标记为已修复`);
    
    // 清空选中
    selectedVulnerabilities.value = [];
  } catch (error) {
    // 用户取消操作或API错误
    if (error !== 'cancel') {
      console.error('批量标记已修复失败:', error);
      ElMessage.error('批量操作失败，请重试');
    }
  } finally {
    loading.value = false;
  }
};

// 批量确认
const batchConfirm = async () => {
  const ids = selectedVulnerabilities.value.map(item => item.id);
  if (ids.length === 0) {
    ElMessage.warning('请先选择要确认的漏洞');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要将选中的 ${ids.length} 个漏洞标记为已确认吗？`,
      '批量操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    );
    
    loading.value = true;
    
    await apiService.batchUpdateVulnerabilityStatus(ids, 'confirmed');
    // 更新本地数据
    const now = new Date().toISOString();
    vulnerabilities.value.forEach(item => {
      if (ids.includes(item.id)) {
        item.status = 'confirmed';
        item.updated_at = now;
      }
    });
    selectedVulnerabilities.value = [];
    ElMessage.success('批量确认成功');
  } catch (error) {
      if (error !== 'cancel') {
        console.error('批量确认失败:', error);
        ElMessage.error('批量操作失败');
      }
    } finally {
      loading.value = false;
    }
  }

// 批量删除
const batchDelete = async () => {
  const ids = selectedVulnerabilities.value.map(item => item.id);
  if (ids.length === 0) {
    ElMessage.warning('请先选择要删除的漏洞');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${ids.length} 个漏洞吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
    );
    
    loading.value = true;
    
    // 调用批量删除API
    await apiService.batchDeleteVulnerabilities(ids);
    
    // 更新本地数据
    vulnerabilities.value = vulnerabilities.value.filter(item => !ids.includes(item.id));
    
    // 如果当前正在查看被删除的漏洞，关闭对话框
    if (currentVulnerability.value && ids.includes(currentVulnerability.value.id)) {
      dialogVisible.value = false;
      currentVulnerability.value = null;
    }
    
    // 清空选中
    selectedVulnerabilities.value = [];
    
    ElMessage.success(`成功删除 ${ids.length} 个漏洞`);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除漏洞失败:', error);
      ElMessage.error('删除失败，请重试');
    }
  } finally {
    loading.value = false;
  }
};

// 搜索漏洞
const searchVulnerabilities = () => {
  // 筛选已通过computed属性实现
  console.log('搜索条件:', searchForm.value);
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.value = {
    keyword: '',
    severity: '',
    status: ''
  };
};

// 处理页码大小变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
};

// 处理当前页码变化
const handleCurrentChange = (current) => {
  pagination.value.currentPage = current;
};

// 组件挂载时加载数据
onMounted(() => {
  loadVulnerabilities();
});
</script>

<style scoped>
.security-vulnerability-container {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-section h2 {
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-container {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-card.total .el-card__header {
  background-color: #409eff;
}

.stat-card.critical .el-card__header {
  background-color: #f56c6c;
}

.stat-card.high .el-card__header {
  background-color: #e6a23c;
}

.stat-card.pending .el-card__header {
  background-color: #67c23a;
}

.stat-content {
  text-align: center;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 16px;
  color: #606266;
}

.search-filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.link-text {
  color: #409eff;
  cursor: pointer;
}

.link-text:hover {
  text-decoration: underline;
}

.vulnerability-details {
  padding: 10px 0;
}

.vulnerability-details .el-descriptions__label {
  font-weight: bold;
  color: #303133;
}

.vulnerability-details .el-descriptions__content {
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 1200px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style>